package web.sms.mvc.service.impl;

import cn.palerock.core.shiro.useradmin.auditor.UserAuditor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import web.sms.core.exception.ServiceException;
import web.sms.core.pojo.ErrorInfo;
import web.sms.mvc.dao.UserMapper;
import web.sms.mvc.entity.User;
import web.sms.mvc.service.UserService;
import web.sms.mvc.service.WechatService;
import web.sms.utils.URLConnectionHelper;

import java.util.List;

/**
 * 时间： 2018/1/31
 *
 * @author Eoly
 */
@Service
public class WechatServiceImpl implements WechatService {

    private String accessToken;
    private final UserService userService;
    private final UserMapper userMapper;
    private final UserAuditor userAuditor;

    @Autowired
    public WechatServiceImpl(UserService userService, UserMapper userMapper, UserAuditor userAuditor) {
        this.userService = userService;
        this.userMapper = userMapper;
        this.userAuditor = userAuditor;
    }

    @Override
    public String getAccessToken(Boolean isReGet) {
        String APPID = "wx5f7c67aed1e686ea";
        String SECRET = "6194fcf6437d2fd1f833938f8977ffdc";
        if (accessToken == null || "".equals(accessToken)) {
            isReGet = true;
        }
        if (isReGet) {
            String resultInfo = URLConnectionHelper.sendGet("https://api.weixin.qq.com/cgi-bin/token",
                    "grant_type=client_credential&appid={0}&secret={1}"
                            .replace("{0}", APPID).replace("{1}", SECRET));
            JSONObject info = JSON.parseObject(resultInfo);
            Integer errcode = (Integer) info.get("errcode");
            if (errcode != null && errcode != 0) {
                throw new ServiceException(new ErrorInfo("获取微信口令失败：{}", 500),
                        info.get("errmsg").toString());
            }
            accessToken = info.get("access_token").toString();
        }
        return accessToken;
    }

    @Override
    public void doBindUser(String loginName, String password) {
        String openid = (String) SecurityUtils.getSubject().getSession().getAttribute("openid");
        if (openid == null || "".equals(openid)) {
            throw new ServiceException(new ErrorInfo("绑定用户失败：{}", 500),
                    "获取用户id失败，请使用微信在公众号中重新进入该页面！");
        }
        User user = userService.findUserWithAuthenticationInfo(loginName);
        if (user == null || user.getUserStatus() <= -2 || password == null || !new Md5Hash(password).toString().equals(user.getUserPassword())) {
            throw new ServiceException(new ErrorInfo("绑定用户失败：{}", 500),
                    "用户名或密码错误！");
        }
        if (!(user.getUserRole().equals("customer") ||
                user.getUserRole().equals("customer_special") ||
                user.getUserRole().equals("driver") ||
                user.getUserRole().equals("worker") ||
                user.getUserRole().equals("sales_manager"))) {
            throw new ServiceException(new ErrorInfo("绑定用户失败：{}", 500),
                    "微信号只能与客户、司机、工人或销售相绑定");
        }
        if (!(user.getUserOpenId() == null || "".equals(user.getUserOpenId()))) {
            throw new ServiceException(new ErrorInfo("绑定用户失败：{}", 500),
                    "该账号已绑定，如若需要继续绑定请在上一次绑定的微信号中申请解绑！");
        }
        // 检查openid是否已绑定
        User conditionUser = new User();
        conditionUser.setUserOpenId(openid);
        List<User> originUsers = userMapper.selectAllUserByAttributes(conditionUser, null);
        if (!originUsers.isEmpty()) {
            throw new ServiceException(new ErrorInfo("绑定用户失败：{}", 500),
                    "您的微信号已绑定，请解绑后再进行该操作！");
        }
        // 绑定
        User changeUser = new User();
        changeUser.setUserOpenId(openid);
        changeUser.setUserId(user.getUserId());
        int result = userMapper.updateByPrimaryKeySelective(changeUser);
        if (result < 1) {
            throw new ServiceException(new ErrorInfo("绑定用户失败：{}", 500),
                    "服务器繁忙,请使用微信在公众号中重新进入该页面！");
        }
    }

    @Override
    public void doFreeUser(String loginName) {
        // 获取当前用户
        User user = userService.getLoggedUser();
        // 若是解绑操作用户自身则不检查权限
        if (user.getUserLoginName().equals(loginName) || loginName == null) {
            loginName = user.getUserLoginName();
        } else {
            // 检查权限
            userAuditor.checkPerms("user:admin");
        }
        // 判断是否绑定微信号
        if (user.getUserOpenId() == null || "".equals(user.getUserOpenId())) {
            throw new ServiceException(new ErrorInfo("解绑微信号失败，{}", 403), "当前用户未绑定微信号！");
        }

        int result = userMapper.updateAttributesToNull(user.getUserId(), "user_open_id");
        if (result < 1) {
            throw new ServiceException(new ErrorInfo("解绑微信号失败：{}", 500),
                    "服务器繁忙,请使用微信在公众号中重新进入该页面！");
        }
    }
}
